package com.bread.bapiclientstater.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.bread.bapiclientstater.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.bread.bapiclientstater.utils.SignUtils.genSign;

/**
 * 调用第三方接口的客户端
 */
public class BApiClient {

    public static final String GATEWAY_HOST="http://localhost:8091";

    private String accessKey;

    private String secretKey;

    public BApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GATEWAY_HOST+"/api/name/getuser", paramMap);
        System.out.println(result);
        return result;
    }


    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(GATEWAY_HOST+"/api/name/postuser/", paramMap);
        System.out.println(result);
        return result;
    }

    private Map<String, String> getHeadMap(String body) {
        Map<String, String> headMap = new HashMap<>();
        headMap.put("nonce", RandomUtil.randomNumbers(4));
        headMap.put("body",body);
        headMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        headMap.put("accessKey", accessKey);
        headMap.put("sign",genSign(body,secretKey));
        return headMap;
    }

    public String getUsernameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse =
                HttpRequest.post(GATEWAY_HOST+"/api/name/restuser/")
                        .addHeaders(getHeadMap(json)).body(json).execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;

    }
}
